package com.cc.openeye.video

import com.cc.openeye.video.VideoConst.FUNCTION_NAME
import com.cc.openeye.video.VideoConst.FUNCTION_NAME_GET_PROGRESS
import com.cc.openeye.video.VideoConst.PARAM_NAME_CURRENT_POSITION
import com.cc.openeye.video.VideoConst.PARAM_NAME_DATA
import com.cc.openeye.video.VideoConst.PARAM_NAME_DURATION
import com.tencent.kuikly.core.base.RenderView
import com.tencent.kuikly.core.nvi.serialization.json.JSONObject
import com.tencent.kuikly.core.views.VideoEvent
import kotlin.math.min

class VideoHelper {

    private var renderView: RenderView? = null
    private var videoEvent: VideoEvent? = null
    private var progressCallBack: ((VideoProgressInfo) -> Unit)? = null

    fun initData(renderView: RenderView?, videoEvent: VideoEvent) {
        this.renderView = renderView
        this.videoEvent = videoEvent
        registerCustomEvent(videoEvent)
    }

    fun getCurrProgress(callBack: (VideoProgressInfo) -> Unit) {
        this.progressCallBack = callBack
        renderView?.callMethod(FUNCTION_NAME_GET_PROGRESS)
    }

    private fun registerCustomEvent(videoEvent: VideoEvent) {
        videoEvent.customEvent {
            val params = it as? JSONObject ?: return@customEvent
            val functionName = params.optString(FUNCTION_NAME) as? String ?: return@customEvent
            when (functionName) {
                FUNCTION_NAME_GET_PROGRESS -> {
                    val data = params.optString(PARAM_NAME_DATA) as? String ?: return@customEvent
                    val dataJson = JSONObject(data)
                    val contentDuration = dataJson.optLong(PARAM_NAME_DURATION)
                    val currentPos = dataJson.optLong(PARAM_NAME_CURRENT_POSITION)
                    val videoProgressInfo = VideoProgressInfo().apply {
                        duration = contentDuration
                        currPosition = min(currentPos, contentDuration)
                        percent = min(currentPos, contentDuration).toFloat() / contentDuration
                    }
                    this.progressCallBack?.invoke(videoProgressInfo)
                }
            }
        }
    }

}